package com.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PublicKey;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.xml.bind.DatatypeConverter;

public class LicenseValidator {

	private static final String CERT_TYPE = "X.509";
	private static Certificate getCertificate(String certificatePath) {
		CertificateFactory certificateFactory;
		try {
			certificateFactory = CertificateFactory.getInstance(CERT_TYPE);
			FileInputStream in = new FileInputStream(certificatePath);
			Certificate certificate = certificateFactory
					.generateCertificate(in);
			in.close();
			return certificate;
		} catch (CertificateException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static PublicKey getPublicKey(String certificatePath) {
		return getCertificate(certificatePath).getPublicKey();
	}

	public static String decryptLicenseByPublicKey(String certificatePath,
			String licenseText) {
		PublicKey key = getPublicKey(certificatePath);

		Cipher cipher;
		try {
			byte[] data = DatatypeConverter.parseBase64Binary(licenseText);
			cipher = Cipher.getInstance(key.getAlgorithm());
			cipher.init(Cipher.DECRYPT_MODE, key);
			StringBuilder sb=new StringBuilder();
			for(int i=0;i<data.length;i+=128){
				int inputLen=128;
				if(i+128>data.length)
					inputLen=data.length-i;
				byte[] temp=cipher.doFinal(data, i, inputLen);
				sb.append(new String(temp));
			}
			return sb.toString();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (NoSuchPaddingException e) {
			e.printStackTrace();
		} catch (InvalidKeyException e) {
			e.printStackTrace();
		} catch (IllegalBlockSizeException e) {
			e.printStackTrace();
		} catch (BadPaddingException e) {
			e.printStackTrace();
		}
		return null;
	}

	
	public static void main(String[] args) {
		System.out.println(decryptLicenseByPublicKey("/tmp/Skycloud.crt", "Mo2ValMRQZzYhNGa0AIkcC5tWSc277CyfmSUc7944Q98KRT9pzUJcgTzNNHSYLQnFGEO9fVo2nqSnLcRf5F7L10LNtlKR20O4KGSTe7flbpcNp6jJiC7n9WUj2JXhMR8Q0TpZqKKmCmvK8l6OsKbdYe7jAclZEnk/NFesezqmX8="));
	}
}
